package AdminService

import (
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/app/service/BaseService"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	"gdshop-admin-go-api/library/tools/cacheHelp"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/grand"
	"time"
)

func Update(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	data := r.GetMap()
	// 修改时间
	data["update_at"] = time.Now().Unix()
	data["dept_id"] = r.GetInt64("departmentId", 0)
	// 增加附加数据
	if req.UpdateInsertData != nil {
		otherData := req.UpdateInsertData(r)
		for k, v := range otherData {
			data[k] = v
		}
	}
	// 删除更新时不需要的字段
	BaseService.DelIgnoreProperty(data, req.UpdateIgnoreProperty)
	// 编辑前方法
	if req.UpdateBeforeFn != nil {
		respRes := req.UpdateBeforeFn(r, data)
		if respRes.Code != 0 {
			return respRes
		}
	}
	// 如果有填写密码时，按修改密码操作
	newPassword := gconv.String(data["password"])
	if len(newPassword) > 0 {
		passwordSalt := grand.Letters(10)
		data["password_salt"] = passwordSalt
		data["password"] = tools.EncryptPassword(newPassword, passwordSalt)
	}
	tx, err := g.DB().Ctx(ctx).Begin()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	obj := tx.Model(req.TableName).Unscoped()
	res, err := obj.Fields(obj.GetFieldsStr()).Where("id", req.Id).Update(data)
	if err != nil {
		tx.Rollback()
		return response.FailByRequestMessage(nil, err.Error())
	}
	row, err := res.RowsAffected()
	if err != nil {
		tx.Rollback()
		return response.FailByRequestMessage(nil, err.Error())
	}
	if row < 1 {
		tx.Rollback()
		return response.FailByRequestMessage(nil, "编辑失败01")
	}

	// 删除 admin_role
	res, err = tx.Model("admin_role").Where("admin_id", req.Id).Delete()
	if err != nil {
		tx.Rollback()
		return response.FailByRequestMessage(nil, err.Error())
	}

	roleIdList := r.GetArray("roleIdList")
	// 插入 admin_role
	rmData := g.List{}
	for _, item := range roleIdList {
		rmData = append(rmData, g.Map{
			"admin_id": req.Id,
			"role_id":  item,
		})
	}
	res, err = tx.Model("admin_role").Insert(rmData)
	if err != nil {
		tx.Rollback()
		return response.FailByRequestMessage(nil, err.Error())
	}
	row, err = res.RowsAffected()
	if row < 1 {
		tx.Rollback()
		return response.FailByRequestMessage(nil, "编辑失败02")
	}
	tx.Commit()

	cacheHelp.ClaerAdminCaches(gconv.String(req.Id))

	return response.SuccessByRequestMessage(nil, "编辑成功")
}
